<template>
  <div class="wang">
    <div class="wang-editor">
      <div ref="toolbar" class="wang-editor-toolbar"></div>
      <div ref="editor" class="wang-editor-text"></div>
    </div>
  </div>
</template>
<script>
import Editor from 'wangeditor'
import { randomString } from '@u/index'
export default {
  name: 'wangEditor',
  props: {
    textHeight: {
      type: Number,
      default: () => {
        return 400
      },
    },
    content: {
      type: String,
      default: () => {
        return ''
      },
    },
  },
  data() {
    return {
      editor: null,
      client: null,
      loading: null,
      key: randomString(40),
      date: '20230715',
    }
  },
  watch: {
    content(val) {
      if (val !== this.editor.txt.html()) {
        this.editor.txt.html(val)
      }
    },
  },
  created() {
    //日期年月日
    const now = new Date()
    const year = now.getFullYear() // 获取当前年份，例如：2023
    const month = now.getMonth() + 1 // 获取当前月份（注意月份是从0开始计数的）
    const day = now.getDate() // 获取当前日期
    const time = new Date().getTime()
    this.date = `${year}${month > 9 ? month : '0' + month}${
      day > 9 ? day : '0' + day
    }-${time}`
    this.$axios
      .get('/admin/upload/getSTS', { showLoading: true })
      .then((data) => {
        if (data.code == 200) {
          this.obj = {
            fileDomain: data.data.endPoint,
            bucket: data.data.buketName,
          }
          const s3Config = {
            accessKeyId: data.data.accessKeyId,
            secretAccessKey: data.data.secretAccessKey,
            endpoint: data.data.endPoint.substring(
              data.data.endPoint.indexOf('//') + 2
            ),
            sessionToken: data.data.sessionToken,
            signatureVersion: 'v4', // 可选v2 或v4
            apiVersion: '2006-03-01',
            s3ForcePathStyle: true,
          }
          this.client = new OOS.S3(s3Config)
        } else {
          this.$message.error(data.msg)
        }
      })
    this.$nextTick(() => {
      this.seteditor()
      this.editor.txt.html(this.content)
    })
  },
  methods: {
    seteditor() {
      let that = this
      this.editor = new Editor(this.$refs.editor)
      this.editor.config.height = this.textHeight
      this.editor.config.zIndex = 0
      // 配置菜单
      this.editor.config.menus = [
        'head', // 标题
        // 'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        // 'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'image', // 插入图片
        // 'table', // 表格
        'video', // 插入视频
        'undo', // 撤销
        'redo', // 重复
        'fullscreen', // 全屏
      ]
      this.editor.config.uploadFileName = 'file' // 后端接受上传文件的参数名
      //  this.editor.config.pasteFilterStyle = false // 取消粘贴样式重置

      this.editor.config.showLinkImg = false //隐藏插入网络图片的功能
      this.editor.config.uploadImgMaxLength = 1 // 限制一次最多上传 1 张图片 */
      this.editor.config.uploadImgMaxSize = 3 * 1024 * 1024 //* 将图片大小限制为 3M 默认为5M /
      //自定义图片上传
      this.editor.config.customUploadImg = (files, insert) => {
        //文件名
        const fileName = `${this.key}.${files[0].name.substring(
          files[0].name.lastIndexOf('.') + 1
        )}`
        this.loading = this.$loading({
          lock: true,
          text: '上传中请等待...',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        this.obj.url = `/${this.obj.bucket}/wangEditor/${this.date}/${fileName}`
        this.client.putObject(
          {
            Body: files[0],
            Bucket: this.obj.bucket,
            Key: `wangEditor/${this.date}/${fileName}`,
          },
          function (err, data) {
            that.loading.close()
            if (err) {
              that.$message.error('操作失败！')
            } else {
              insert(that.obj.fileDomain + that.obj.url)
              that.$message.success('操作成功！')
            }
          }
        )
      }

      this.editor.config.showLinkVideo = false //隐藏插入网络视频的功能
      this.editor.config.uploadVideoTimeout = 1000 * 60 * 35
      this.editor.config.uploadVideoMaxSize = 5 * 1024 * 1024 // 5M
      this.editor.config.uploadVideoName = 'file'
      this.editor.config.uploadVideoAccept = ['mp4', 'ogg', 'avi', 'mkv']
      /* 自定义图片和视频上传（支持跨域和非跨域上传，简单操作）*/
      this.editor.config.customUploadVideo = (files, insert) => {
        //文件名
        const fileName = `${this.key}.${files[0].name.substring(
          files[0].name.lastIndexOf('.') + 1
        )}`
        this.loading = this.$loading({
          lock: true,
          text: '上传中请等待...',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        this.obj.url = `/${this.obj.bucket}/wangEditor/${this.date}/${fileName}`
        this.client.putObject(
          {
            Body: files[0],
            Bucket: this.obj.bucket,
            Key: `wangEditor/${this.date}/${fileName}`,
          },
          function (err, data) {
            that.loading.close()
            if (err) {
              that.$message.error('操作失败！')
            } else {
              insert(that.obj.fileDomain + that.obj.url)
              that.$message.success('操作成功！')
            }
          }
        )
      }
      this.editor.config.onchange = (html) => {
        this.$emit('getContent', html) // 将内容同步到父组件中
      }
      // 创建富文本编辑器
      this.editor.create()
    },
  },
}
</script>
